#!/bin/bash

test "${ACTION}" = "add" -o "${ACTION}" = "remove" || exit 0
echo "${DEVNAME}" | grep -E "^/dev/input/event[0-9]+$" || exit 0

WIIMOTEMODE=$(batocera-settings-get controllers.wiimote.mode)
test "${WIIMOTEMODE}" != 'gun' -a "${WIIMOTEMODE}" != "" && exit 0 # gun mode not enabled

# if case a nunchuk is removed, try to transform into a wiigun
if test "${ACTION}" = "remove"
then
    DEVSFILE=$(grep -REl '^'${DEVNAME}'$' /var/run/virtual-wiigun-devices.*.devs 2>/dev/null | head -1)
    if test -n "${DEVSFILE}"
    then
	# kill the evdev if still here
	PIDFILE=$(echo "${DEVSFILE}" | sed -e s+"\.devs$"+".pid"+)
	LPID=$(cat "${PIDFILE}")
	kill -15 "${LPID}"
	echo -1 > "${PIDFILE}"
	# fake to add one of the other device
	DEVNAME=$(grep -vE '^'${DEVNAME}'$' "${DEVSFILE}" | head -1)
    else
	exit 0
    fi
fi
# ##### ##### ##### ##### ##### ##### ##### ##### ##### #####

PARENTHASH=$(evsieve-helper parent "${DEVNAME}" input hid)
BASEFILE="/var/run/virtual-wiigun-devices.${PARENTHASH}"
PIDFILE="${BASEFILE}.pid"
LOCKFILE="${BASEFILE}.lock"
LOGFILE="${BASEFILE}.log"
MODEFILE="${BASEFILE}.mode"
DEVSFILE="${BASEFILE}.devs"

unlockAndExit() {
    rmdir "${LOCKFILE}"
    exit "${1}"
}

checkRunningPIDAndExit1() {
    test ! -e "${PIDFILE}" && return 0
    LPID=$(cat "${PIDFILE}")
    test ! -d "/proc/${LPID}" && return 0
    unlockAndExit 1
}

trylock() {
    # lock
    N=0
    while ! mkdir "${LOCKFILE}"
    do
	sleep 1
	let N++
	test "${N}" -gt 30 && exit 1 # give up
    done
}

breakVirtualGunOnDifferentMode() {
    test ! -e "${PIDFILE}" && return 0
    LPID=$(cat "${PIDFILE}")
    test ! -d "/proc/${LPID}" && return 0

    # break
    CURRENT_MODE=$(cat "${MODEFILE}")
    HASNUN=$(if echo "${CHILDREN}" | grep -qE 'Nintendo Wii Remote Nunchuk$'; then echo 1; else echo 0; fi)
    if test "${HASNUN}" = 1 -a "${CURRENT_MODE}" = "gun"
    then
	kill -15 "${LPID}"
	echo -1 > "${PIDFILE}"
    fi
    # the zapper will be dead automatically, when the device nunchuk is removed
}

trylock
CHILDREN=$(evsieve-helper children "${PARENTHASH}" input hid)

breakVirtualGunOnDifferentMode
checkRunningPIDAndExit1

HASIR=$( if echo "${CHILDREN}" | grep -qE 'Nintendo Wii Remote IR$';      then echo 1; else echo 0; fi)
HASACCEL=$( if echo "${CHILDREN}" | grep -qE 'Nintendo Wii Remote Accelerometer$';      then echo 1; else echo 0; fi)
HASJOY=$(if echo "${CHILDREN}" | grep -qE 'Nintendo Wii Remote$';         then echo 1; else echo 0; fi)
HASNUN=$(if echo "${CHILDREN}" | grep -qE 'Nintendo Wii Remote Nunchuk$'; then echo 1; else echo 0; fi)

MODEGUN=0
MODEZAPPER=0

test "${HASIR}" = 1 -a "${HASJOY}" = 1 -a "${HASNUN}" = 0 && MODEGUN=1
test "${HASIR}" = 1 -a "${HASJOY}" = 1 -a "${HASNUN}" = 1 && MODEZAPPER=1

# Trigger (B)              : BTN_EAST
# A                        : BTN_SOUTH
# Plus (+)                 : KEY_NEXT
# Minus (-)                : KEY_PREVIOUS
# 1                        : BTN_1
# 2                        : BTN_2
# Home (calibration)       : BTN_MODE
# D-pad                    : BTN_5, BTN_6, BTN_7, BTN_8

if test "${MODEGUN}" = 1
then
    DEV1=$(echo "${CHILDREN}" | grep -E 'Nintendo Wii Remote IR$' | head -1 | cut -f 1)
    DEV2=$(echo "${CHILDREN}" | grep -E 'Nintendo Wii Remote$'    | head -1 | cut -f 1)
    DEV3=$(echo "${CHILDREN}" | grep -E 'Nintendo Wii Remote Accelerometer$' | head -1 | cut -f 1)

    nohup evsieve --input "${DEV1}" "${DEV2}" persist=exit --map abs:hat0x abs:x:1023-x --map abs:hat0y abs:y --map key:next btn:middle --map btn:east btn:left --map btn:south btn:right --map btn:2 btn:3 --map btn:1 btn:2 --map key:previous btn:1  --map btn:mode btn:4 --map key:up btn:5 --map key:down btn:6 --map key:left btn:7 --map key:right btn:8 --block key:previous --block key:next --input "${DEV3}" --output name="Wii Gun" >/dev/null 2>"${LOGFILE}" &
    echo $! > "${PIDFILE}"
    echo "gun" > "${MODEFILE}"
else
    if test "${MODEZAPPER}" = 1
    then
	DEV1=$(echo "${CHILDREN}" | grep -E 'Nintendo Wii Remote IR$'      | head -1 | cut -f 1)
	DEV2=$(echo "${CHILDREN}" | grep -E 'Nintendo Wii Remote$'         | head -1 | cut -f 1)
	DEV3=$(echo "${CHILDREN}" | grep -E 'Nintendo Wii Remote Nunchuk$' | head -1 | cut -f 1)
	DEV4=$(echo "${CHILDREN}" | grep -E 'Nintendo Wii Remote Accelerometer$' | head -1 | cut -f 1)
	nohup evsieve --input "${DEV1}" "${DEV2}" persist=exit --map yield abs:hat0x abs:x:1023-x --map yield abs:hat0y abs:y --map yield key:next btn:middle --map yield btn:east btn:left --map yield btn:south btn:right --map yield btn:2 btn:3 --map yield btn:1 btn:2 --map yield key:previous btn:1  --map yield btn:mode btn:4 --map yield key:up btn:5 --map yield key:down btn:6 --map yield key:left btn:7 --map yield key:right btn:8 --block key:previous --block key:next --input "${DEV3}" --map yield btn:c btn:right --map yield btn:z btn:left --block abs:rx abs:ry abs:rz --map yield abs:hat0x:-30~..~-31 btn:7:1 --map yield abs:hat0x:~-31..-30~ btn:7:0 --map yield abs:hat0x:~30..31~ btn:8:1 --map yield abs:hat0x:31~..~30 btn:8:0 --block abs:hat0x --map yield abs:hat0y:-30~..~-31 btn:6:1 --map yield abs:hat0y:~-31..-30~ btn:6:0 --map yield abs:hat0y:~30..31~ btn:5:1 --map yield abs:hat0y:31~..~30 btn:5:0 --block abs:hat0x abs:hat0y --input "${DEV4}" --output name="Wii Zapper" >/dev/null 2>"${LOGFILE}" &
	echo $! > "${PIDFILE}"
	echo "zapper" > "${MODEFILE}"
	echo "${DEV1}"  > "${DEVSFILE}"
	echo "${DEV2}" >> "${DEVSFILE}"
	echo "${DEV3}" >> "${DEVSFILE}"
	echo "${DEV4}" >> "${DEVSFILE}"
    else
	unlockAndExit 1
    fi
fi

unlockAndExit 0
